﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using RFIDStockManagement.Model.InterFace;
using RFIDStockManagement.Model.Public;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraPrinting;
using DevExpress.XtraBars;
using DevExpress.XtraPrinting.Preview;
using RFIDStockManagement.Common.Public.Enums;

namespace RFIDStockManagement.Client.Report
{
    public partial class ReportControl : DevExpress.XtraEditors.XtraUserControl
    {
        private IReport _thisReport;
        private ReportPlugIn _PlugIn;

       
        protected PrintingSystem _PrintSystem = null;
        protected PrintableComponentLink _PrintLink = null;


        /// <summary>
        /// 报表
        /// </summary>
        public IReport ThisReport
        {
            get { return _thisReport; }
            set { _thisReport = value; }
        }
        /// <summary>
        ///报表插件
        /// </summary>
        public ReportPlugIn PlugIn
        {
            get { return _PlugIn; }
        }

        public ReportControl()
        {
            InitializeComponent();
            this.bandedGridView1.CustomDrawRowIndicator += new DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventHandler(view_CustomDrawRowIndicator);

        }

        private void view_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {

            if (e.Info.IsRowIndicator)
            {
                if (e.RowHandle >= 0)
                {
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
                }

            }
        }

        /// <summary>
        /// 刷新column
        /// </summary>
        public void RefreshColumns()
        {
            if (this.ThisReport == null) return;

            BandedGridColumn newCol;
            GridBand newBand;
            GridBand newBand2;
            if (ThisReport == null) return;

            gridControl1.DataSource = null;
            
            bandedGridView1.BeginUpdate();
            bandedGridView1.Columns.Clear();
            bandedGridView1.Bands.Clear();

            foreach (ReportColumn x in ThisReport.Columns)
            {
                newBand = new GridBand();
                newCol = new BandedGridColumn();
                newCol.FieldName = x.FieldName;
                newBand.Caption = x.Caption;
                newCol.Caption = x.Caption;
                if (x.Width > 0)
                {
                    newCol.Width = x.Width;
                    newBand.Width = x.Width;
                }

                if (x.Index > 0)
                {
                    newCol.VisibleIndex = x.Width;
                    //newBand.VisibleIndex = x.Width;
                }

                newCol.Visible = x.Visible;
                newBand.Visible = x.Visible;
                newCol.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                newBand.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                newBand.AppearanceHeader.Font = new System.Drawing.Font("宋体", 11, System.Drawing.FontStyle.Bold);
                newBand.AppearanceHeader.Options.UseTextOptions = true;

                switch (x.ColumnType)
                {
                    case EnumDataTypes.TNumeric:
                        newCol.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                        break;
                    case EnumDataTypes.TDateTime:
                        newCol.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                        break;
                    default:
                        break;
                }

                newCol.DisplayFormat.FormatString = x.FormateString;

                bandedGridView1.Bands.Add(newBand);
                if (x.SonColumns.Count == 0) //这里不需要把包含子列的列加进去
                {
                    newCol.OwnerBand = newBand;
                }

                foreach (ReportColumn xx in x.SonColumns)
                {
                    newBand2 = new GridBand();
                    newCol = new BandedGridColumn();
                    newCol.FieldName = xx.FieldName;
                    newBand2.Caption = xx.Caption;
                    newCol.Caption = xx.Caption;
                    newCol.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                    newCol.Visible = xx.Visible;
                    newBand2.Visible = xx.Visible;
                    switch (xx.ColumnType)
                    {
                        case EnumDataTypes.TNumeric:
                            newCol.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                            break;
                        case EnumDataTypes.TDateTime:
                            newCol.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                            break;
                        default:
                            break;
                    }

                    newCol.DisplayFormat.FormatString = xx.FormateString;

                    newBand2.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                    newBand2.AppearanceHeader.Font = new System.Drawing.Font("宋体", 11, System.Drawing.FontStyle.Bold);
                    newBand2.AppearanceHeader.Options.UseTextOptions = true;

                    newBand.Children.Add(newBand2);
                    bandedGridView1.Columns.Add(newCol);
                    newCol.OwnerBand = newBand2;

                }

            }

            bandedGridView1.EndUpdate();
        }
       
        private void ReportControl_Load(object sender, EventArgs e)
        {
            bandedGridView1.OptionsView.ShowColumnHeaders = false;
            bandedGridView1.OptionsCustomization.AllowSort = true;

            RefreshColumns();
            ShowFilter();
            this.FindForm().Activate();
        }


        /// <summary>
        /// 显示过滤界面
        /// </summary>
        private void ShowFilter()
        {

            if (_PlugIn != null)
            {
                if (_PlugIn.ShowFilter(string.Empty))
                {
                    if (_thisReport != null)
                    {
                        _thisReport.Filters = _PlugIn.Filter.Filters;
                        RefreshData();
                    }
                }
            }
        }


        private void bar_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string key = e.Item.Name.ToLower();

            if (DoPlugInItemClick(sender, key)) //如果插件响应了事件且cancel了后边的事件,就不继续执行
            {
                return;
            }
            try
            {
                switch (key)
                {
                    case "barrefresh":
                        RefreshData();
                        break;
                    case "barprint":
                        //DoPrint();
                        try
                        {
                            bandedGridView1.Print();
                        }
                        catch
                        {
                            throw new Exception("打印机未知异常,请检查打印机设置或重新打印");
                        }
                        break;
                    case "barprintpreview":
                        
                        try
                        {
                            DoPrintPreview();
                        }
                        catch
                        {
                            throw new Exception("打印机未知异常,请检查打印机设置或重新打印");
                        }
                        break;
                    case "barfilter":
                        ShowFilter();
                        break;
                    default:

                        break;
                }
            }
            catch (Exception ex)
            {
                AlertForm.ShowError(ex.Message);
            }
        }


        public void RefreshData()
        {
            if (_thisReport != null)
            {
                DataTable curReportData = _thisReport.GetReportData();
                gridControl1.DataSource = curReportData;
            }
        }

        private void DoPrintPreview()
        {
            string headCaption = string.Empty ;
            InitPrinter();
            PageHeaderFooter phf = _PrintLink.PageHeaderFooter as PageHeaderFooter;

            phf.Header.Content.Clear();
            if (_PlugIn != null)
            {
                headCaption = _PlugIn.ReportHeader;
            }
            if (string.IsNullOrEmpty(headCaption))
            {
                headCaption = _thisReport.ReportCaption;
            }

            phf.Header.Content.AddRange(new string[] { "", headCaption, "" });
            phf.Header.Font = new System.Drawing.Font("宋体", 14, System.Drawing.FontStyle.Bold); phf.Header.LineAlignment = BrickAlignment.Center;
            phf.Footer.Content.AddRange(new string[]{"","","[Page # of Pages #]"});
            _PrintLink.CreateDocument();
            _PrintSystem.PreviewFormEx.ShowInTaskbar = false;
            _PrintSystem.PreviewFormEx.Text = "打印预览";
            _PrintSystem.PreviewFormEx.ShowDialog();
            
           

        }

        private void InitPrinter()
        {
            if (_PrintSystem == null)
            {
                _PrintSystem = new DevExpress.XtraPrinting.PrintingSystem();
                _PrintLink = new DevExpress.XtraPrinting.PrintableComponentLink(_PrintSystem);

                _PrintSystem.Links.Add(_PrintLink);
                _PrintLink.Component = gridControl1;

                _PrintSystem.PreviewFormEx.PrintBarManager.AllowCustomization = false;
                _PrintSystem.PreviewFormEx.PrintBarManager.AllowQuickCustomization = false;
                _PrintSystem.PreviewFormEx.PrintBarManager.AllowShowToolbarsPopup = false;
                foreach (DevExpress.XtraBars.BarItem x in _PrintSystem.PreviewFormEx.PrintBarManager.Items)
                {
                    if (x.Caption == "Search")
                    {
                        x.Visibility = BarItemVisibility.Never;

                        continue;
                    }

                    if (x is PrintPreviewBarItem)
                    {
                        x.Caption = RepairSubCaption(x.Caption);
                    }
                    if (x is PrintPreviewSubItem)
                    {
                        x.Caption = RepaireCaption(x.Caption);
                    }
                }
                
            }
        }

        private string RepaireCaption(string caption)
        {
            string rC = caption.Replace("File","文件");
            rC = rC.Replace("&View", "视图");
            rC = rC.Replace("&Background", "背景");
            rC = rC.Replace("Page Layout", "页面布局");
            return rC;
        }

        private string RepairSubCaption(string caption)
        {
            string rC = caption.Replace("Page Set&up", "页面设置");
            rC = rC.Replace("&Print", "打印设置");
            rC = rC.Replace("P&rint", "打印");
            rC = rC.Replace("Export Document", "导出文档");
            rC = rC.Replace("Send via E-Mail", "发送邮件");
            rC = rC.Replace("E&xit", "退出");
            rC = rC.Replace("&Color", "颜色");
            rC = rC.Replace("&Watermark", "水印工具");
            rC = rC.Replace("Header And Footer", "页眉页脚");
            
            return rC;
        }

        /// <summary>
        /// 响应报表插件事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private bool DoPlugInItemClick(object sender, string key)
        {
            bool isCanceled = false;

            if (_PlugIn != null)
            {
                if (_PlugIn.OnBarClick != null)
                {
                    _PlugIn.OnBarClick(sender, key, ref isCanceled);
                }
            }

            return isCanceled;
        }

        /// <summary>
        /// 设置当前报表插件
        /// </summary>
        /// <param name="plugIn"></param>
        public void SetPlugIn(ReportPlugIn plugIn)
        {
            _PlugIn = plugIn;
            plugIn.Owner = this;
            DevExpress.XtraBars.BarItem newBar;
            foreach (ReportBarItem x in plugIn.Bars)
            {
                newBar = new DevExpress.XtraBars.BarButtonItem();
                newBar.Caption = x.Caption;
                newBar.Name = x.Key;
                newBar.Visibility = x.Visible ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never;
                barManager1.Items.Add(newBar);
                newBar.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(bar_ItemClick);
                this.bar1.LinksPersistInfo.Add(new LinkPersistInfo(newBar));
            }

        }

        /// <summary>
        /// 禁用或启用bar工具条
        /// </summary>
        /// <param name="enabled"></param>
        public void EnableBar(bool enabled)
        {
            foreach (DevExpress.XtraBars.BarItem x in barManager1.Items)
            {
                x.Enabled = enabled;
            }
        }

        /// <summary>
        /// 禁用某个工具条
        /// </summary>
        /// <param name="barName"></param>
        /// <param name="enabled"></param>
        public void EnableBar(string barName, bool enabled)
        {
            foreach (DevExpress.XtraBars.BarItem x in barManager1.Items)
            {
                if (x.Name == barName)
                {
                    x.Enabled = enabled;
                    break;
                }
            }
        }
    }
}
